﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace GoodStuff.Heartbeat.Core.Sensors
{
    public class SqlConnectionSensor : ISensor
    {
        private string _connectionString;
        private SensorChannel _connectionChannel;

        /// <summary>
        /// Warning: you should set a really low connection-timeout otherwise the sensor might block.
        /// </summary>
        /// <param name="connectionString"></param>
        public SqlConnectionSensor(string connectionString)
        {
            _connectionString = connectionString;
            _connectionChannel = new SensorChannel() { Description = "Connection", Units = "bool", DefaultLow = 0, DefaultHigh = float.MaxValue, Value = 0.0f };
        }

        public string Name
        {
            get { return "SQL Connection"; }
        }

        public void Update()
        {
            try
            {
                //try to connect to the database. 
                using (SqlConnection conn = new SqlConnection(_connectionString))
                {                   
                    conn.Open();
                    SqlCommand cmd = new SqlCommand("select count(*) from sysobjects", conn);
                    cmd.ExecuteNonQuery();
                    _connectionChannel.Value = 1.0f;
                    conn.Close();
                }
            }
            catch
            {
                _connectionChannel.Value = 0.0f;
            }
        }

        public IEnumerable<ISensorChannel> Values
        {
            get
            {
                yield return _connectionChannel; 
            }
        }
    }
}
